from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import DATABASE_URL

# 配置数据库连接池
# pool_size：连接池中的初始连接数量
# max_overflow：超出 pool_size 后允许的最大连接数
# pool_timeout：连接池获取连接的超时时间（秒）
# pool_recycle：连接在多长时间后会被回收（秒）
engine = create_engine(
    DATABASE_URL,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30,
    pool_recycle=3600
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()